#include "elloading.h"
#include <QPaintEvent>
#include <QPainter>
#include "eltheme.h"

const int ElLoading::Spacing = 3;

ElLoading::ElLoading(QWidget *target)
{
    setTarget(target);
    setIcon(new ElIcon(":/icons/loading.svg", this));
    initPalette();
}

ElLoading::ElLoading(QWidget *target, const QString &text)
    : ElLoading{target}
{
    setText(text);
}

void ElLoading::setTarget(QWidget *target)
{
    setParent(target);
    resize(target->size());
}

QWidget *ElLoading::target() const
{
    return dynamic_cast<QWidget *>(parent());
}

QString ElLoading::text() const
{
    return _text;
}

void ElLoading::setText(const QString &text)
{
    if (_text == text)
        return;
    _text = text;
}

QColor ElLoading::background() const
{
    return _bg;
}

void ElLoading::setBackground(const QColor &bgColor)
{
    if (_bg == bgColor)
        return;
    _bg = bgColor;
    initPalette();
}

ElIcon *ElLoading::icon() const
{
    return _icon;
}

void ElLoading::setIcon(ElIcon *icon)
{
    if (_icon == icon)
        return;
    delete _icon;
    _icon = icon;
    _icon->fillBackground(ThemeColor::primaryColor);
}

void ElLoading::setIcon(const QString &filename, int iconSize)
{
    delete _icon;
    _icon = new ElIcon(filename, this);
    _icon->resize(iconSize, iconSize);
    _icon->fillBackground(ThemeColor::primaryColor);
}

void ElLoading::paintEvent(QPaintEvent *e)
{
    QPainter painter(this);
    auto icon_size = _icon->size().width();
    QRectF br;
    painter.drawText(QRect(), Qt::AlignCenter, _text, &br);
    auto icon_text_h = icon_size + Spacing + br.height();
    _icon->move((width() - icon_size) / 2, (height() - icon_text_h) / 2);
    _icon->show();
    painter.setBrush(_palette.color(ElPalette::Background));
    painter.setPen(_palette.color(ElPalette::Background));
    painter.drawRect(rect());
    painter.setPen(_palette.color(ElPalette::Foreground));
    QRectF drawing_rect((width() - br.width()) / 2,
                        _icon->y() + icon_size + Spacing,
                        br.width(),
                        br.height());
    painter.drawText(drawing_rect, Qt::AlignCenter, _text);
    e->accept();
}

void ElLoading::showEvent(QShowEvent *e)
{
    emit appeared();
    e->accept();
}

void ElLoading::hideEvent(QHideEvent *e)
{
    emit disappeared();
    e->accept();
}

void ElLoading::closeEvent(QCloseEvent *e)
{
    emit disappeared();
    e->accept();
}

void ElLoading::mouseReleaseEvent(QMouseEvent *e)
{
    auto pos = e->pos();
    if (pos.x() >= 0 && pos.x() <= width() && pos.y() >= 0 && pos.y() <= height()) {
        emit clicked();
    }
}

void ElLoading::initPalette()
{
    _palette.setColor(ElPalette::Background, _bg);
    _palette.setColor(ElPalette::Foreground, ThemeColor::primaryColor);
}
